package com.ddgame.xiaomi;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.xiaomi.ad.mediation.MMAdConfig;
import com.xiaomi.ad.mediation.MMAdError;
import com.xiaomi.ad.mediation.bannermimo.MMAdBanner;
import com.xiaomi.ad.mediation.bannermimo.MMBannerAd;
import com.xiaomi.ad.mediation.fullscreeninterstitial.MMAdFullScreenInterstitial;
import com.xiaomi.ad.mediation.fullscreeninterstitial.MMFullScreenInterstitialAd;
import com.xiaomi.ad.mediation.internal.config.IMediationConfigInitListener;
import com.xiaomi.ad.mediation.mimonew.MIMOAdSdkConfig;
import com.xiaomi.ad.mediation.mimonew.MiMoNewSdk;
import com.xiaomi.ad.mediation.rewardvideoad.MMAdReward;
import com.xiaomi.ad.mediation.rewardvideoad.MMAdRewardVideo;
import com.xiaomi.ad.mediation.rewardvideoad.MMRewardVideoAd;

import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;


/**
 * desc   : 模版
 * author : chendaning
 * date   : 1/5/22
 */
public class XMBaseActivity extends AppCompatActivity implements View.OnClickListener {
    private SharedPreferences mSharedPreferences;
    private static final String PRIVACY_FILE = "privacy_file";
    private static final String PRIVACY_KEY = "privacy_key";

    private static final String AD_TAG_ID = "28e12557924f47bcde1fb4122527a6bc";
    private MMAdBanner mAdBanner;
    private ViewGroup mContainer;
    private MMBannerAd mBannerAd;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initXiaomi();
    }

    protected void setBannerContainer(ViewGroup container){
        this.mContainer = container;
    }

    protected View getTestUI(){
        View view = LayoutInflater.from(this).inflate(R.layout.fragment_banner_ad, null);
        mContainer = view.findViewById(R.id.view_ad_container);
        mAdBanner = new MMAdBanner(this, AD_TAG_ID);
        mAdBanner.onCreate();
        Button requestBanner = view.findViewById(R.id.view_request_ads_button);
        requestBanner.setTag(101);
        requestBanner.setOnClickListener(this);


        Button showBtn = view.findViewById(R.id.view_show_ads_button);
        showBtn.setTag(100);
        showBtn.setOnClickListener(this);

        Button requestInter = view.findViewById(R.id.request_inter_button);
        requestInter.setTag(102);
        requestInter.setOnClickListener(this);

        Button showInter = view.findViewById(R.id.show_inter_button);
        showInter.setTag(103);
        showInter.setOnClickListener(this);

        Button requestSplash = view.findViewById(R.id.request_splash_button);
        requestSplash.setTag(104);
        requestSplash.setOnClickListener(this);

        Button showSplash = view.findViewById(R.id.show_splash_button);
        showSplash.setTag(105);
        showSplash.setOnClickListener(this);


        Button requestVideo = view.findViewById(R.id.request_video_button);
        requestVideo.setTag(106);
        requestVideo.setOnClickListener(this);

        Button showVideo = view.findViewById(R.id.show_video_button);
        showVideo.setTag(107);
        showVideo.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        int tag = (int) v.getTag();
        switch (tag) {
        case 100:
            showBannerAd();
            break;
        case 101:
            destroyBanner();
            loadBannerAd();
            break;
        case 102:
            requestInterAd();
            break;
        case 103:
            showInterAd();
            break;
        case 104:

            break;
        case 105:

            break;
        case 106:
            requestVideoAd();
            break;
        case 107:
            showVideoAd();
            break;

        default:
            break;
        }
    }

    private void loadBannerAd() {
        mContainer.removeAllViews();
        MMAdConfig adConfig = new MMAdConfig();
        adConfig.supportDeeplink = true;
        // 必选参数 设置广告图片的最大尺寸及期望的图片宽高比，单位Px
        adConfig.imageWidth = 320;
        adConfig.imageHeight = 160;
        /**
         * 推荐 设置
         *   600 * 90
         *  如果有遮挡问题 可以尝试 360*54 300*45 等比例
         */
        adConfig.viewWidth = 300;
        adConfig.viewHeight = 30;
        adConfig.setBannerContainer(mContainer);//传入banner view容器 建议宽高自适应
        adConfig.setBannerActivity(this);
        mAdBanner.load(adConfig, new MMAdBanner.BannerAdListener() {
            @Override
            public void onBannerAdLoaded(List<MMBannerAd> list) {
                showToast("onBannerAdLoaded success");
                if (list != null && list.size() > 0) {
                    mBannerAd = list.get(0);

                    if(mContainer != null) {
                        showBannerAd();
                    }
                }
            }

            @Override
            public void onBannerAdLoadError(MMAdError error) {
                showToast("onBannerAdLoadError");
            }
        });
    }

    private void showBannerAd() {
        mBannerAd.show(new MMBannerAd.AdBannerActionListener() {
            @Override
            public void onAdShow() {

            }
            @Override
            public void onAdClicked() {
                showToast("ad_click");
            }

            @Override
            public void onAdDismissed() {
                showToast("ad_dismiss");
            }

            @Override
            public void onAdRenderFail(int code, String msg) {
                showToast("ad_load_error");
            }
        });
    }

    protected void showToast(String text){
        Toast.makeText(XMBaseActivity.this, text,
                Toast.LENGTH_LONG).show();
    }

    public void destroyBanner() {
        if (mBannerAd != null) {
            mBannerAd.destroy();
        }
    }

    private void initXiaomi(){
        mSharedPreferences = this.getSharedPreferences(PRIVACY_FILE, MODE_PRIVATE);
        boolean isAgree = mSharedPreferences.getBoolean(PRIVACY_KEY, false);
        if (!isAgree) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("用户须知");
            builder.setMessage("在使用本应用的过程中，我们将联网并向您申请以下权限：\n获取手机号、IMEI\n读写设备上的照片及文件");
//            builder.setIcon(org.cocos2dx.lib.R.mipmap.ic_launcher);
            builder.setCancelable(false);            //点击对话框以外的区域是否让对话框消失

            //设置正面按钮
            builder.setPositiveButton("同意", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    editor.putBoolean(PRIVACY_KEY, true);
                    editor.apply();
                    initMiMoNewSdk();
                    dialog.dismiss();
                }
            });
            //设置反面按钮
            builder.setNegativeButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    System.exit(0);
                    dialog.dismiss();
                }
            });
            AlertDialog dialog = builder.create();

            Window window = dialog.getWindow();
            window.setGravity(Gravity.BOTTOM);

            WindowManager m = getWindowManager();
            Display d = m.getDefaultDisplay();
            WindowManager.LayoutParams p = dialog.getWindow().getAttributes();
            p.width = d.getWidth();
            dialog.getWindow().setAttributes(p);

            dialog.show();
        } else {
            initMiMoNewSdk();
        }
    }

    private void initMiMoNewSdk() {
        requestPermission();
        MiMoNewSdk.init(getApplicationContext(), "2882303761517973922", getString(R.string.app_name),
                new MIMOAdSdkConfig.Builder()
                        .setDebug(true)
                        .setStaging(true).build(), new IMediationConfigInitListener() {
                    @Override
                    public void onSuccess() {
                        showToast("mediation config init success");
                    }

                    @Override
                    public void onFailed(int errorCode) {
                        showToast("mediation config init failed");
                    }
                });
    }

    private void requestPermission() {
        try {
            TTAdSdk.getAdManager().requestPermissionIfNecessary(this);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //判断该应用是否有写SD卡权限，如果没有再去申请
                if (ContextCompat.checkSelfPermission(this, Manifest.permission
                        .WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_PHONE_STATE}, 100);
                }
            }
            int permissionLocation = ActivityCompat
                    .checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
                String[] location = {Manifest.permission.ACCESS_FINE_LOCATION};
                ActivityCompat.requestPermissions(this, location, 1);
            }
            int permissionPhone = ActivityCompat
                    .checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
            if (permissionPhone != PackageManager.PERMISSION_GRANTED) {
                String[] phoneState = {Manifest.permission.READ_PHONE_STATE};
                ActivityCompat.requestPermissions(this, phoneState, 1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /****************************************请求插屏广告****************************************/
    private static String HRO_AD_TAG_ID = "756c0d2cdb935266522249c90ca04dbe";
    private static String VER_AD_TAG_ID = "b539ee9934e2e869c6aced477a02fa0e";
    private static String HRO_HALF_VIDEO_AD_TAG_ID = "922f067280f0a74a66e2fd6cd54cb35e";
    private static String HRO_HALF_VIDEO_IMG_AD_TAG_ID = "727d0a5942a7add7550df158c57a3744";
    private static String VER_HALF_VIDEO_AD_TAG_ID = "1c8250c1beef950f74a6e456b6282bf0";
    private static String VER_HALF_VIDEO_IMG_AD_TAG_ID = "93961437543f4859107c2d58f25ba4a4";
    private MMAdFullScreenInterstitial mVerFullScreenInterstitialAd;
    private MMFullScreenInterstitialAd mMMFullScreenInterstitialAd;
    public void requestInterAd() {
        if(mVerFullScreenInterstitialAd == null) {
            mVerFullScreenInterstitialAd = new MMAdFullScreenInterstitial(getApplication(), VER_AD_TAG_ID);
        }
        MMAdConfig adConfig = new MMAdConfig();
        adConfig.supportDeeplink = true;
        adConfig.imageHeight = 1920;
        adConfig.imageWidth = 1080;
        //期望广告view的size,单位dp（*必填）
        adConfig.viewWidth = 1080;
        adConfig.viewHeight = 1920;
        adConfig.setInsertActivity(this);
        mVerFullScreenInterstitialAd.load(adConfig, new MMAdFullScreenInterstitial.FullScreenInterstitialAdListener() {
            @Override
            public void onFullScreenInterstitialAdLoaded(
                    MMFullScreenInterstitialAd ad) {
                if (ad == null) {
                    showToast("onFullScreenInterstitialAdLoaded but null");
                } else {
                    showToast("onFullScreenInterstitialAdLoaded success");
                    mMMFullScreenInterstitialAd = ad;
                }
            }

            @Override
            public void onFullScreenInterstitialAdLoadError(MMAdError error) {
                showToast("onFullScreenInterstitialAdLoadError");
            }
        });
    }

    public void showInterAd() {
        showToast(mMMFullScreenInterstitialAd == null ? "ad null" : "ad not null");
        if(mMMFullScreenInterstitialAd != null && !mMMFullScreenInterstitialAd.isExpired()) {
            mMMFullScreenInterstitialAd.setInteractionListener(
                    new MMFullScreenInterstitialAd.FullScreenInterstitialAdInteractionListener() {
                        @Override
                        public void onAdShown(MMFullScreenInterstitialAd mmFullScreenInterstitialAd) {
                        }

                        @Override
                        public void onAdClicked(MMFullScreenInterstitialAd mmFullScreenInterstitialAd) {

                        }

                        @Override
                        public void onAdVideoComplete(MMFullScreenInterstitialAd mmFullScreenInterstitialAd) {

                        }

                        @Override
                        public void onAdClosed(MMFullScreenInterstitialAd mmFullScreenInterstitialAd) {
                            requestInterAd();
                        }

                        @Override
                        public void onAdVideoSkipped(MMFullScreenInterstitialAd mmFullScreenInterstitialAd) {

                        }

                        @Override
                        public void onAdRenderFail(MMFullScreenInterstitialAd mmFullScreenInterstitialAd, int i,
                                                   String s) {
                            mMMFullScreenInterstitialAd = null;
                        }
                    });
            mMMFullScreenInterstitialAd.showAd(this);
        } else {
            requestInterAd();
        }
    }

    /****************************************请求开屏广告****************************************/

    public void requestSplashAd() {

    }

    public void showSplashAd() {

    }

    /****************************************请求视频广告****************************************/
    private static String AD_VIDEO_TAG_ID = "95297e164e1dfb6c0ce4a2eaf61cc791";
    private MMAdRewardVideo mAdRewardVideo;
    private MMRewardVideoAd mMMRewardVideoAd;
    public void requestVideoAd() {
        if(mAdRewardVideo == null) {
            mAdRewardVideo = new MMAdRewardVideo(getApplication(), AD_VIDEO_TAG_ID);
        }
        MMAdConfig adConfig = new MMAdConfig();
        adConfig.supportDeeplink = true;
        adConfig.imageHeight = 1920;
        adConfig.imageWidth = 1080;
        //期望广告view的size,单位dp（*必填）
        adConfig.viewWidth = 1080;
        adConfig.viewHeight = 1920;
        adConfig.rewardCount = 5;
        adConfig.rewardName = "金币";
        adConfig.userId = "test1234";
        adConfig.setRewardVideoActivity(this);
        mAdRewardVideo.load(adConfig, new MMAdRewardVideo.RewardVideoAdListener() {
            @Override
            public void onRewardVideoAdLoaded(MMRewardVideoAd ad) {
                if (ad != null) {
                    mMMRewardVideoAd = ad;
                    showToast("onRewardVideoAdLoaded ad success");
                } else {
                    showToast("onRewardVideoAdLoaded ad null");
                }
            }

            @Override
            public void onRewardVideoAdLoadError(MMAdError error) {
                showToast("onRewardVideoAdLoadError");
            }
        });
    }

    public void showVideoAd() {
        if(mMMRewardVideoAd != null) {
            mMMRewardVideoAd.setInteractionListener(
                    new MMRewardVideoAd.RewardVideoAdInteractionListener() {
                        @Override
                        public void onAdShown(MMRewardVideoAd mmRewardVideoAd) {
                            showToast("onAdShown");
                        }

                        @Override
                        public void onAdClicked(MMRewardVideoAd mmRewardVideoAd) {
                            showToast("onAdClicked");
                        }

                        @Override
                        public void onAdError(MMRewardVideoAd mmRewardVideoAd, MMAdError error) {
                            showToast("onAdError");
                        }

                        @Override
                        public void onAdVideoComplete(MMRewardVideoAd mmRewardVideoAd) {
                            showToast("onAdVideoComplete");
                        }

                        @Override
                        public void onAdClosed(MMRewardVideoAd mmRewardVideoAd) {
                            showToast("onAdClosed");
                        }

                        @Override
                        public void onAdReward(MMRewardVideoAd mmRewardVideoAd, MMAdReward mmAdReward) {
                            showToast("onAdReward");
                            onAdRewardFinish();
                        }

                        @Override
                        public void onAdVideoSkipped(MMRewardVideoAd mmRewardVideoAd) {
                            showToast("onAdVideoSkipped");
                        }
                    });
            mMMRewardVideoAd.showAd(this);
        }

    }

    protected void onAdRewardFinish(){

    }
}
